from flask_login import login_required, current_user
from flask import current_app, flash, redirect, url_for, render_template

from app.libs.enums import PendingStatus
from app.models.base import db
from app.models.drift import Drift
from app.models.gifts import Gift
from app.view_model.gift import MyGifts
from . import web


@web.route('/my/gift')
@login_required
def my_gifts():
    uid = current_user.id
    # 我的全部礼物
    gifts_of_me = Gift.get_user_gifts(uid)
    gifts_isbn_list = [gift.isbn for gift in gifts_of_me]
    # 我的礼物有几人想要
    wish_count_list = Gift.get_wish_counts(gifts_isbn_list)
    gifts_view_model = MyGifts(gifts_of_me, wish_count_list)
    return render_template('my_gifts.html', gifts=gifts_view_model.gifts)


@web.route('/gifts/book/<isbn>')
@login_required
def save_to_gifts(isbn):
    if current_user.can_save_to_list(isbn):
        with db.auto_commit():
            gift = Gift()
            gift.isbn = isbn
            gift.uid = current_user.id
            # current_user.beans += 0.5
            current_user.beans += current_app.config['BEANS_UPLOAD_ONE_BOOK']
            db.session.add(gift)
        #     db.session.commit()
        # except Exception as e:
        #     db.session.rollback()
        #     raise e
    else:
        flash('已经添加到赠送清单或者心愿清单，不要重复添加！')
    return redirect(url_for('web.book_detail', isbn=isbn))


@web.route('/gifts/<gid>/redraw')
@login_required
def redraw_from_gifts(gid):
    gift = Gift.query.filter_by(id=gid, launched=False).first_or_404()
    drift = Drift.query.filter_by(gift_id=gid, pending=PendingStatus.WAITING).first()
    if drift:
        flash('请先完成鱼漂交易')
    else:
        with db.auto_commit():
            current_user.beans -= current_app.config['BEANS_UPLOAD_ONE_BOOK']
            gift.delete()
    return redirect(url_for('web.my_gifts'))
